package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: ApUserSearchServiceImpl
 * @time: 2022/7/10
 */
@Service
public class ApUserSearchServiceImpl {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveUserSearch(Integer userId,String equipmentId,String keyword){
        ApUserSearch userSearch = new ApUserSearch();
        userSearch.setUserId(userId);
        userSearch.setEquipmentId(equipmentId);
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());
        Query query = new Query();
        Criteria criteria = Criteria.where("keyword").is(keyword);
        if(userId==0){
            criteria.and("equipmentId").is(equipmentId);
        }else{
            criteria.and("userId").is(userId);
        }
        long count = mongoTemplate.count(query, ApUserSearch.class);
        if(count == 0){
            mongoTemplate.save(userSearch);
        }
    }

    public ResponseResult loadHistory(ApArticleSearchDto dto) {
        User user = UserThreadLocalUtil.get();
        Query query = new Query();
        Criteria criteria = new Criteria();
        if(user.getUserId()==0){
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }else{
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.skip(0);
        query.limit(5);
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    public ResponseResult delHistory(ApArticleSearchDto dto) {
        List<ApUserSearch> hisList = dto.getHisList();
        List<String> list = new ArrayList<>();
        for (ApUserSearch userSearch : hisList) {
            list.add(userSearch.getId());
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").in(list));
        mongoTemplate.remove(query, ApUserSearch.class);
        return ResponseResult.okResult();
    }
}
